package com.com.knowledgepaymentmanagementsystem.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.com.knowledgepaymentmanagementsystem.utils.JwtUtils;
import com.com.knowledgepaymentmanagementsystem.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //1.强转servletRequest与servletResponse获取请求的url
//        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
//        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String url = httpServletRequest.getRequestURI().toString();
        log.info("请求的url" + url);

        //2.判断url中是否含有login ，有就放
        if(url.contains("login")){
            log.info("有login");
//            filterChain.doFilter(servletRequest,servletResponse);
            return true;
        }

        //3.获取token
        String jwt = httpServletRequest.getHeader("token");
        log.info("得到token");
        //4.判断令牌是否存在，不存在则返回错误结果（未登录）

        if (!StringUtils.hasLength(jwt)){
            log.info("请求头为空，返回未登录信息");
            ResultUtil error = new ResultUtil(500,"Sorry you do not have this permission");
            //将对象手动转换为json------》阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            httpServletResponse.getWriter().write(notLogin);
            return false;

        }

        //5.解析token，失败则返回错结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败，返回未登录信息");
//            Result error = Result.error("NOT_LOGIN");
            ResultUtil error = new ResultUtil(500,"Sorry you do not have this permission");
            //将对象手动转换为json------》阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            httpServletResponse.getWriter().write(notLogin);
            return false;
        }


        //6.放行
        log.info("令牌合法，放行");
//        filterChain.doFilter(servletRequest,servletResponse);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
